package com.tsp.ssm.controller;

import Utils.verification;

import java.io.*;
import java.net.URLEncoder;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.tsp.ssm.mapper.CeituserliMapperCustom;
import com.tsp.ssm.po.Ceituserli;
import com.tsp.ssm.po.CeituserliExample;
import com.tsp.ssm.po.Landuserli1;
import com.tsp.ssm.service.ItemsService;
import com.tsp.ssm.service.signupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import static Utils.verification.*;

/**
 * Created by 隼 on 2016/12/4.
 */
@Controller
@RequestMapping( value = "/sun" )
public class testController {


    @RequestMapping(value ="/ramdonImg", method ={RequestMethod.GET,RequestMethod.POST} )
    //返回随机验证图片
    public void ramdonImg(HttpServletRequest request,HttpServletResponse response,Model model)throws Exception{
        response.setContentType("image/jpeg");      //设置输出类型
        String randomString =getRandomString();  //随机字符串
        request.getSession(true).setAttribute("randomString", randomString);    //放到session中
        int width=100;
        int height =30;
        Color color=getRandomColor();   //随机颜色，用于背景色
        Color reverse=getReverseColor(color);    //反色，用于前景色

        BufferedImage bi=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);    //创建一个彩色图片

        Graphics2D g=bi.createGraphics();   //获取绘图对象
        g.setFont(new Font("SansSerif",Font.BOLD,16));      //设置字体
        g.setColor(color);
        g.fillRect(0, 0, width, height);  //绘制背景
        g.setColor(reverse);    //设置颜色
        g.drawString(randomString, 18, 20);          //绘制随机字符
        for(int i=0;i<100;i++){
            //画最多100个噪音点
            g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);     //随机噪音点
            ServletOutputStream out=response.getOutputStream();   //转陈JPEG格式
            JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);   ///编码器
            encoder.encode(bi);  //对图片进行编码
            out.flush();   //输出到客户端
        }
    }

    @RequestMapping( value = "/showImg" , method = RequestMethod.GET)
    //展示随机验证码
    public String showImg(){
        return "test/identity_1";
    }


    @RequestMapping("/CustInfoDemo")
    public void CustInfoDemo(HttpServletRequest request,HttpServletResponse response) throws Exception{
        /*
		 * getRequestURL方法返回客户端发出请求完整URL
		 *getRequestURI方法返回请求行中的资源名部分
		 *getQueryString 方法返回请求行中的参数部分
		 *getRemoteAddr方法返回发出请求的客户机的IP地址
		 *getMethod得到客户机请求方式
		 *getContextPath 获得当前web应用虚拟目录名称

		 *
		 * */
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the GET method"+"<br/>");
        //获取客户端请求的完整URL
        String url=request.getRequestURL().toString();
        out.println(url+"<br/>");
        //获取客户端请求的资源名称
        String uri=request.getRequestURI();
        out.println(uri+"<br/>");
        //获取请求行中的参数部分
        String qstr=request.getQueryString();
        out.println(qstr+"<br/>");
        //获取请求客户端的IP地址
        String ip=request.getRemoteAddr();
        out.println(ip+"<br/>");
        //获取客户机的请求方式
        String Method=request.getMethod();
        out.println(Method+"<br/>");
        //获得当前web应用虚拟目录名称
        String webname=request.getContextPath();
        out.println(webname+"<br/>");
        out.flush();
        out.close();

    }

    @RequestMapping( value = "/HeadDemo" )
    public void HeadDemo(HttpServletRequest request,HttpServletResponse response) throws Exception{
        /*
		 * request获取请求头信息
		 *
		 * 获得客户机请求头
		 *getHeader(name)方法 --- String
		 *getHeaders(String name)方法 --- Enumeration<String>
		 *getHeaderNames方法 --- Enumeration<String>
		 *获得具体类型客户机请求头
		 *getIntHeader(name)方法  --- int
		 *getDateHeader(name)方法 --- long(日期对应毫秒
		 *
		 * */


        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Enumeration<String> enumeration=request.getHeaderNames();
        while(enumeration.hasMoreElements()){
            String name=enumeration.nextElement();
            String value=request.getHeader(name);
            out.println("<br/>name"+name+"  value "+value);

        }
        out.flush();
        out.close();

    }

    @RequestMapping( value = "/RefreshDemo" )
    public void RefreshDemo(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setCharacterEncoding("UTF-8");        //设置response编码方式
        request.setCharacterEncoding("UTF-8");         //设置request编码方式
        //控制是否进行缓存______不缓存
		/*
		 * response.setIntHeader("expires", -1);
		 *	response.setHeader("Cache-Control", "no-cache");
		 *	response.setHeader("Pragma", "no-cache");
		 *	response.setDateHeader("Expires", System.currentTimeMillis()+1000l*3600*24*30);
		 *
		 *
		 * */
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        //自动 刷新
        out.println(new Date().toLocaleString());
        response.setHeader("Refresh", "1");
//        out.println("三秒后返回主页");
//        response.setHeader("Refresh", "3;url="+request.getContextPath());
        out.flush();
        out.close();
    }

    @RequestMapping( value = "/RedirectDemo" )
    public void RedirectDemo(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setContentType("text/html");
		/*
		 * 重定向
		 * */
//		response.setStatus(302);
//		response.setHeader("Location", "/Tomcat_Demo");
        response.sendRedirect("/sun/RefreshDemo");
    }

    @RequestMapping( value = "/DownServlet" )
    public void DownServlet(HttpServletRequest request,HttpServletResponse response) throws Exception{
        /*
		 * 下载
		 * */

        //response.setHeader("Content-Disposition", "attachment; filename=1.jpg");
        //URL编码方式——————利用这种算法将ascii码中没有的字符转换为ascii码中有的字符表示的形式
        response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode("美女.jpg", "utf-8"));
        InputStream in=new FileInputStream("I:\\MyIDEACeit\\SpringmvcDemo\\src\\main\\webapp\\WEB-INF\\html\\WingNan\\1.jpg");
        OutputStream out=response.getOutputStream();
        byte[] bs=new byte[1024];
        int i=0;
        while((i=in.read(bs))!=-1){
            out.write(bs, 0, i);
        }
        in.close();
    }


    //cookiedemo
    @RequestMapping( value = "/cookiedemo" , method = RequestMethod.GET)
    public void cookiedemo(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setContentType("text/html;charset=utf-8");

        Cookie []  cs = request.getCookies();
        Cookie findC = null;
        if(cs!=null){
            for(Cookie c : cs){
                if("lastTime".equals(c.getName())){
                    findC = c;
                }
            }
        }
        if(findC == null){
            response.getWriter().write("您是第一次访问本网站!");
        }else{
            Long lastTime = Long.parseLong(findC.getValue());
            response.getWriter().write("您上次访问时间是:"+new Date(lastTime).toLocaleString());
        }

        Date date = new Date();
        Cookie c = new Cookie("lastTime",date.getTime()+"");
        c.setMaxAge(3600*24*30);
        c.setPath(request.getContextPath());
        //c.setDomain(".baidu.com");
        response.addCookie(c);

    }


    //注册服务器
    @Autowired
    private signupService signupService;
    @RequestMapping( value = "/signDemo_1Service" , method = RequestMethod.POST)
    public void signDemo_1(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String MIname=request.getParameter("MIname");
        //System.out.println(MIname);
        String password=request.getParameter("password");
        String sex=request.getParameter("Sex");
        String birthday=request.getParameter("birthday");
        String phonenb=request.getParameter("phonenb");
        String img=request.getParameter("indentity");
        String  zzz= (String) request.getSession(true).getAttribute("randomString");               //验证码

        System.out.println("img"+img+zzz);
        if(!img.equals(zzz)){
            StringBuffer b=new StringBuffer();
            b.append("<my>");
            b.append("<pass>NO</pass>");
            b.append("<how>验证码错误</how>");
            b.append("</my>");
            System.out.println(b.toString());
            out.println(b.toString());
        }else {
            Landuserli1 landuserli1 = null;
            try {
                landuserli1 = signupService.findItemsByN(MIname);
                if (landuserli1 == null) {
                    landuserli1 = new Landuserli1();
                    //System.out.println("zzz");
                    landuserli1.setMiname(MIname);
                    System.out.println(birthday);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
                    landuserli1.setBirthday(sdf.parse(birthday));
                    landuserli1.setPassword(password);
                    landuserli1.setPhonenb(phonenb);
                    landuserli1.setSex(sex);
                    signupService.addUser(landuserli1);
                    System.out.println("注册成功");
                    StringBuffer b = new StringBuffer();
                    b.append("<my>");
                    b.append("<pass>YES</pass>");
                    b.append("<how>注册成功</how>");
                    b.append("</my>");
                    System.out.println(b.toString());
                    out.println(b.toString());


                } else {
                    System.out.println(landuserli1.toString());
                    System.out.println("用户已经存在");
                    StringBuffer b = new StringBuffer();
                    b.append("<my>");
                    b.append("<pass>NO</pass>");
                    b.append("<how>用户已存在</how>");
                    b.append("</my>");
                    System.out.println(b.toString());
                    out.println(b.toString());
                }


            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("连接数据库出错");
                StringBuffer b = new StringBuffer();
                b.append("<my>");
                b.append("<pass>NO</pass>");
                b.append("<how>连接数据库出错</how>");
                b.append("</my>");
                System.out.println(b.toString());
                out.println(b.toString());

            }
        }
        out.flush();
        out.close();

    }
    //注册界面
    @RequestMapping( value = "/signDemo_1" , method = RequestMethod.GET)
    public String signDemo_1(){
        return "test/landDemo_1/SignUp";
    }

    //登录页面
    @RequestMapping( value = "/landDemo_1" , method = RequestMethod.GET)
    public String land(){return "test/landDemo_1/land";}

    //登录服务器
    @RequestMapping( value = "/landS" , method = RequestMethod.POST)
    public void lands(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        //提交上来的用户名和密码
        String name=request.getParameter("name");
        String password=request.getParameter("password");
        Landuserli1 landuserli1=null;
        landuserli1 = signupService.findItemsByN(name);
        if(landuserli1==null){
            StringBuffer b=new StringBuffer();
            b.append("<my>");
            b.append("<pass>NO</pass>");
            b.append("<how>用户不存在</how>");
            b.append("</my>");
            System.out.println(b.toString());
            out.println(b.toString());
        }else{
            String spassword=landuserli1.getPassword();
            if(spassword.equals(password)){
                StringBuffer b=new StringBuffer();
                b.append("<my>");
                b.append("<pass>YES</pass>");
                b.append("<how>登录成功</how>");
                b.append("</my>");
                System.out.println(b.toString());
                out.println(b.toString());
            }else{
                StringBuffer b=new StringBuffer();
                b.append("<my>");
                b.append("<pass>NO</pass>");
                b.append("<how>密码错误</how>");
                b.append("</my>");
                System.out.println(b.toString());
                out.println(b.toString());
            }
        }
        out.flush();
        out.close();
    }


    //增删改查
    //list页面
    @RequestMapping(value ="/userlist", method ={RequestMethod.GET,RequestMethod.POST} )
    public ModelAndView userlist( ) throws Exception {
       List<CeituserliMapperCustom> userlist=signupService.suserlist(null) ;

        ModelAndView modelAndView =  new ModelAndView();
        //相当 于request的setAttribut，在jsp页面中通过itemsList取数据
       modelAndView.addObject("userlist", userlist);
        //指定视图
        modelAndView.setViewName("/test/landDemo_1/Userlist");
        return modelAndView;
    }


    //批量删除
    @RequestMapping(value ="/drop", method ={RequestMethod.POST} )
    public  void dropuser(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String sql="";
        sql=request.getParameter("sql");
        System.out.println("zzzzzzzzz");
        if(sql==""||sql==null){
            StringBuffer b=new StringBuffer();
            b.append("<pass>参数错误</pass>");
            System.out.println(b.toString());
            out.println(b.toString());
        }else{
            signupService.deleteuser(sql);
            StringBuffer b=new StringBuffer();
            b.append("<pass>删除成功</pass>");
            System.out.println(b.toString());
            out.println(b.toString());
        }
        out.flush();
        out.close();

    }
    @RequestMapping(value ="/addpage", method ={RequestMethod.GET} )
    public  String addpage(){
        //I:\MyIDEACeit\SpringmvcDemo\src\main\webapp\WEB-INF\jsp\test\landDemo_1\adduser.jsp
        return "test/landDemo_1/adduser";
    }

    @RequestMapping(value ="/add", method ={RequestMethod.POST} )
    public  String adduser(HttpServletRequest request, HttpServletResponse response,
                         MultipartFile photo//接收商品图片
    ) throws Exception{
        String name=request.getParameter("name");
        String sex=request.getParameter("sex");
        String birth=request.getParameter("time");
        String cclass=request.getParameter("cclass");
        String aihao=request.getParameter("aihao");
       System.out.println(birth);
        Ceituserli ceituserli=new Ceituserli();
        ceituserli.setName(name);
        ceituserli.setSex(sex);
        String[] d=birth.split("-");
        //System.out.println(Integer.parseInt(d[0], 10)-1900+""+Integer.parseInt(d[1], 10)+""+Integer.parseInt(d[2], 10));
      // Date data =new Date(Integer.parseInt(d[0], 10)-1900,Integer.parseInt(d[1], 10),Integer.parseInt(d[2], 10));
        ceituserli.setBirthday(new Date(Integer.parseInt(d[0], 10)-1900,Integer.parseInt(d[1], 10),Integer.parseInt(d[2], 10)));
        ceituserli.setCclass(cclass);
        ceituserli.setAihao(aihao);



        //原始名称
        String originalFilename = photo.getOriginalFilename();
        //上传图片
        String newFileName=null;
        if(photo!=null && originalFilename!=null && originalFilename.length()>0){
            //存储图片的物理路径F:\Work___Space\apache-tomcat-8.0.36\webapps\img
            String pic_path = "F:\\Work___Space\\apache-tomcat-8.0.36\\webapps\\img\\";
            //新的图片名称
            newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            System.out.println(pic_path+newFileName);
            //新图片
            File newFile = new File(pic_path+newFileName);
            //将内存中的数据写入磁盘
            photo.transferTo(newFile);
            //将新图片名称写到user中
            System.out.println(newFileName);
        }else{
            System.out.println("null");
        }
        ceituserli.setPhoto(newFileName);
        signupService.adduser(ceituserli);
        return "redirect:userlist";
    }


    @RequestMapping(value ="/alterS", method ={RequestMethod.GET} )
    public  String alters(Model model ,HttpServletRequest request, HttpServletResponse response
    ) throws Exception {
        String id=request.getParameter("id");
        System.out.println(id);
        Ceituserli ceituserli=signupService.selcetonebykey(Integer.parseInt(id));
        model.addAttribute("user",ceituserli);
        return "test/landDemo_1/alter";
    }
    @RequestMapping(value ="/alter", method ={RequestMethod.POST} )
    public String alter(HttpServletRequest request, HttpServletResponse response,
                        MultipartFile photo//接收商品图片
                         )throws  Exception{
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        String name=request.getParameter("name");
        String id=request.getParameter("id");
        String sex=request.getParameter("sex");
        String birth=request.getParameter("time");
        String cclass=request.getParameter("cclass");
        String aihao=request.getParameter("aihao");
        Ceituserli ceituserli=new Ceituserli();
        ceituserli.setId(Integer.parseInt(id));
        ceituserli.setName(name);
        ceituserli.setSex(sex);
        String[] d=birth.split("-");
        //System.out.println(Integer.parseInt(d[0], 10)-1900+""+Integer.parseInt(d[1], 10)+""+Integer.parseInt(d[2], 10));
        // Date data =new Date(Integer.parseInt(d[0], 10)-1900,Integer.parseInt(d[1], 10),Integer.parseInt(d[2], 10));
        ceituserli.setBirthday(new Date(Integer.parseInt(d[0], 10)-1900,Integer.parseInt(d[1], 10),Integer.parseInt(d[2], 10)));
        ceituserli.setCclass(cclass);
        ceituserli.setAihao(aihao);
        //原始名称
        String originalFilename = photo.getOriginalFilename();
        //上传图片
        String newFileName=null;
        if(photo!=null && originalFilename!=null && originalFilename.length()>0){
            //存储图片的物理路径F:\Work___Space\apache-tomcat-8.0.36\webapps\img
            String pic_path = "F:\\Work___Space\\apache-tomcat-8.0.36\\webapps\\img\\";
            //新的图片名称
            newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            System.out.println(pic_path+newFileName);
            //新图片
            File newFile = new File(pic_path+newFileName);
            //将内存中的数据写入磁盘
            photo.transferTo(newFile);
            //将新图片名称写到user中
            System.out.println(newFileName);
        }else{
            System.out.println("null");
        }
        ceituserli.setPhoto(newFileName);
        signupService.alteruser(ceituserli);
        return "redirect:userlist";
    }


    @RequestMapping(value ="/jspdemo1", method ={RequestMethod.GET} )
    public String jspdemo1(){
        return "test/learnjsp/index";

    }
    @RequestMapping(value ="/dealwith", method ={RequestMethod.POST} )
    public String dealwith(){
        return "test/learnjsp/demo1";

    }
    @RequestMapping(value ="/application", method ={RequestMethod.GET} )
    public String application(){
        return "test/learnjsp/application";

    }

}
